package vip.zhenzicheng.test.juc.lock.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;

/**
 * @author zhenzicheng
 * @date 2023-02-07 14:47
 */
@Slf4j
public class CyclicBarrierCase {

  /**
   * 屏障，达到屏障内最大线程数时，同时释放这一组的线程
   */
  public static void main(String[] args) {
    final int threadCount = 10;
    CyclicBarrier cyclicBarrier = new CyclicBarrier(threadCount, () -> {
      log.info("线程:" + Thread.currentThread().getName() + ",完成最后任务");
    });
    for (int i = 0; i < threadCount; i++) {
      new Task(cyclicBarrier).start();
    }
  }

  static class Task extends Thread {
    CyclicBarrier cyclicBarrier;

    Task(CyclicBarrier cyclicBarrier) {
      this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
      try {
        Thread.sleep(1000);
        System.out.println(getName() + " 到达栅栏 A");
        this.cyclicBarrier.await();
        System.out.println(getName() + " 冲破栅栏 A");

        Thread.sleep(2000);
        System.out.println(getName() + " 到达栅栏 B");
        this.cyclicBarrier.await();
        System.out.println(getName() + " 冲破栅栏 B");
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}
